const { getBlogDetail } = require('../api/blog');
const fs = require('fs');

const source = require('../../blog_list_source.json');

const handleBlogDetail = () => {
  const list = JSON.parse(fs.readFileSync('./need_detail.json'));
  let errList = [];
  list.forEach((id, index) => {
    const time = (index + 1) * 800 * Math.random();
    console.log(`第${index + 1}条详情将在${time / 1000}s后开始获取`);
    setTimeout(() => {
      getBlogDetail(id)
        .then(res => {
          const { longTextContent } = res.data;
          console.log(`成功获取第${index + 1}条完整内容`);
          const toReplace = source.find(item => item.mblogid === id);
          if (toReplace) {
            toReplace.text_raw = longTextContent;
          }
        })
        .catch(err => {
          console.log(`第${index + 1}条出错了,已将id记录`, id);
          errList.push(id);
        });
    }, time);
  });
  const maxTime = list.length * 800 + 5000;
  console.log(`等待${maxTime / 1000}s后再次处理`);

  setTimeout(() => {
    if (errList.length) {
      console.log('重新获取获取失败的微博详情');
      fs.writeFileSync('./need_detail.json', JSON.stringify(errList));
      handleBlogDetail();
      errList = [];
    } else {
      console.log('开始重新写入源数据');
      fs.writeFileSync('./need_detail.json', JSON.stringify(errList));
      fs.writeFileSync('./blog_list_source.json', JSON.stringify(source));
      console.log('全部写入完成');
    }
  }, maxTime);
};
module.exports = handleBlogDetail;
